/**
 * 
 */
package com.qolome.mail;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.InputStreamResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.multipart.MultipartFile;

import com.qolome.mail.model.SendIndo;
import com.qolome.utils.web.AjaxResult;

/**
 * @Description: Java邮件
 * @author 姜锋
 * @date 2018年6月17日 下午6:36:56
 * @version V1.0
 */
public class MailUtil {
	/**
	 * @Description: 发送邮件 不负责非空校验
	 * @author 姜锋
	 * @date 2018年6月22日 上午10:06:44
	 * @param @param sendinfo
	 * @param @return
	 * @return AjaxResult
	 * @throws MessagingException 
	 */
	public AjaxResult sendMail(SendIndo sendInfo)  {
		StringBuffer exceptionMsg = new StringBuffer();
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setHost(sendInfo.getSendHost());
		mailSender.setUsername(sendInfo.getSendUsername());
		mailSender.setPassword(sendInfo.getSendPassword());
		if(sendInfo.getSendPort()!= null){
			mailSender.setPort(sendInfo.getSendPort());
		}
		MimeMessage msg = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true);
			helper.setFrom(sendInfo.getSendUsername());
			helper.setTo(sendInfo.getRecipients());
			helper.setSubject(sendInfo.getSubject());
			if (sendInfo.isHtml()) {
				helper.setText(sendInfo.getSendText(), true);
			} else {
				helper.setText(sendInfo.getSendText());
			}
			if (null != sendInfo.getAttachment() && sendInfo.getAttachment().length != 0) {
				MultipartFile[] attachment = sendInfo.getAttachment();
				for (int i = 0; i < attachment.length; i++) {
					helper.addAttachment(attachment[i].getName(), new InputStreamResource(attachment[i].getInputStream()));
				}
			}
			mailSender.send(msg);
			return AjaxResult.returnMessage(true,"发送成功");
		} catch (MessagingException mme) {
			exceptionMsg.append("发生异常: MimeMessageHelper /n");
		}catch(IOException ie){
			exceptionMsg.append("发生异常: IOException");
		}
		return AjaxResult.returnMessage(false, exceptionMsg.toString());
	}
}
